package com.bybops.ui.activity

import android.app.Activity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import baseproject.com.mybaseproject.net.ApiErrorModel
import baseproject.com.mybaseproject.net.ResultObserver
import baseproject.com.mybaseproject.net.RetrofitManager
import baseproject.com.mybaseproject.ui.base.BaseActivity
import baseproject.com.mybaseproject.utils.scheduler.RxUtils
import com.bybops.R
import com.bybops.app.MyApplication
import com.bybops.model.bean.EquipmentList
import com.bybops.net.BaseResponse
import com.bybops.utils.BlueToothUtils
import com.bybops.utils.CommUtils
import com.bybops.utils.TimeUtils
import kotlinx.android.synthetic.main.activity_poll_check_detail.*
import kotlinx.android.synthetic.main.toolbar_base.*
import kotlinx.android.synthetic.main.toolbar_base.view.*

/**
 * 巡检详情界面
 */
class PollCheckDetailActivity : BaseActivity(){


    private var equipmentList: EquipmentList? = null
    //当前电量
    private var mVoltage: String? = null
    //当前锁的状态
    private var mLockStatus = false

    override fun getLayoutId(): Int? {
        return R.layout.activity_poll_check_detail
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar.titleBar(R.id.mToolBar)
                .navigationBarColor(R.color.colorPrimaryDark)
                .init()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initData()
        initView()
        addListener()
    }

    private fun initData() {
        equipmentList = intent.getSerializableExtra("EquipmentList") as EquipmentList
    }

    private fun initView() {
        mToolBar.mTitle.text = "巡检详情"
        closeOrder.isClickable = false
        closeOrder.isEnabled = false
        //设置数据
        //设备id
        tv_operation_name.text = "设备ID：" + equipmentList?.barcode
        //锁的状态
        when (equipmentList?.equipStatus) {
            // 使用中 是开着的
            EquipmentList.LockStatus.USERING -> imageLockStatus.setImageResource(R.mipmap.icon_unlock)
            //其他状态视为锁的状态
            else -> imageLockStatus.setImageResource(R.mipmap.icon_locked)
        }
        //电量文本
        ltvLastEnergyText.text = BlueToothUtils.getEnergyText(equipmentList?.energy)
        //电量图标
        ltvLastEnergyIcon.setImageResource(BlueToothUtils.getEnergyResourceId(equipmentList?.energy))
        //医院
        stvHospital.rightTextView.text = equipmentList?.hospital
        //科室  病床
        stvAddress.rightTextView.text = equipmentList?.department
        //责任人
        stvDailyMan.rightTextView.text = equipmentList?.userName
        //巡检时间  默认是客户端当前时间
        stvTime.rightTextView.text = TimeUtils.commLongToString(TimeUtils.dateFormat_4, System.currentTimeMillis())
    }

    private fun addListener() {
        //返回按钮
        RxUtils.rxClick(mToolBar.mBtnBack, object : RxUtils.OnClickInterf {
            override fun onViewClick(view: View) {
                finish()
            }
        })
        //点击开锁按钮
        RxUtils.rxClick(llLockStatus, object : RxUtils.OnClickInterf {
            override fun onViewClick(view: View) {
                //点击开锁按钮
                if (!mLockStatus) {
                    //当前为关闭状态
                    showProgress("正在开锁...")
                    BlueToothUtils.openLock(equipmentList?.lockName, object : BlueToothUtils.LockStatusInf {
                        override fun openLock(isOpenSuccess: Boolean) {
                            mLockStatus = isOpenSuccess
                            if (mLockStatus) {
                                //当前为开的状态
                                tvLockStatus.text = "关锁确认"
                            }
                            hideProgress()
                        }

                        override fun openFail(msg: String?) {
                            showToast(msg)
                            hideProgress()
                        }

                        override fun currVoltageAndStatus(voltage: String?, lockStatus: Boolean) {}

                        override fun connectStatus(connected: Boolean) {}
                    })
                } else {
                    //读取当前锁是否已经关闭
                    showProgress("正在关锁...")
                    BlueToothUtils.readLockStatus(equipmentList?.lockName, object : BlueToothUtils.LockStatusInf {
                        override fun openLock(isOpenSuccess: Boolean) {}

                        override fun openFail(msg: String?) {
                            showToast(msg)
                            hideProgress()
                        }

                        override fun currVoltageAndStatus(voltage: String?, lockStatus: Boolean) {
                            mLockStatus = lockStatus
                            mVoltage = voltage
                            if (lockStatus) {
                                //未关闭
                                showToast("请先手动关闭锁")
                                tvLockStatus.text = "关锁确认"
                            } else {
                                //已经关闭  启用关闭工单按钮
                                tvLockStatus.text = "点击开锁"
                                closeOrder.isClickable = true
                                closeOrder.isEnabled = true
                                closeOrder.setShapeSolidColor(resources.getColor(R.color.color_2c9cf0))
                                closeOrder.setUseShape()
                            }
                            hideProgress()
                        }

                        override fun connectStatus(connected: Boolean) {}
                    })
                }
            }
        })
        //关闭工单按钮
        RxUtils.rxClick(closeOrder, object : RxUtils.OnClickInterf {
            override fun onViewClick(view: View) {
                if (TextUtils.isEmpty(etPollDesc.text.toString()?.trim())) {
                    showToast("请输入巡检情况")
                    return
                }
                var params = HashMap<String, String?>()
                params["equipSN"] = equipmentList?.equipSN
                params["access_token"] = MyApplication.instance?.mAccessToken
                params["barcode"] = equipmentList?.barcode
                params["energy"] = mVoltage
                params["userKey"] = equipmentList?.userKey
                params["userName"] = equipmentList?.userName
                params["hospital"] = equipmentList?.hospital
                params["hospitalId"] = equipmentList?.hospitalId
                params["department"] = equipmentList?.department
                params["lockName"] = equipmentList?.lockName
                params["startequipStatus"] = equipmentList?.equipStatus?.toString()
                params["endequipStatus"] = "1"
                params["faultTime"] = equipmentList?.faultTime?.toString()
                params["faultDes"] = equipmentList?.faultDes
                params["faultUrl"] = equipmentList?.faultUrl
                params["pollTime"] = System.currentTimeMillis().toString()
                params["pollUrl"] = ""
                params["pollDes"] = etPollDesc.text.toString()?.trim()

                showProgress("")
                RetrofitManager.apiService.pollingAddPoll(CommUtils.getNotNullHashMap(params))
                        .compose(RxUtils.io2main())
                        .subscribeWith(object : ResultObserver<String>() {
                            override fun success(data: BaseResponse<String>) {
                                showToast(data.resultMsg)
                                hideProgress()
                                setResult(Activity.RESULT_OK)
                                finish()
                            }

                            override fun failure(statusCode: Int, apiErrorModel: ApiErrorModel) {
                                showToast(apiErrorModel.message)
                                hideProgress()
                            }
                        })

            }
        })
    }
}